<?php

class NewsController extends AdminController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actionView($id) {
        $news_tag_criteria = new CDbCriteria;
        $news_tag_criteria->condition = "news_tag_news_id = '{$id}'";
        $news_tag_model = site_news_tag::model()->findAll($news_tag_criteria);
        $news_tag = '';
        if ($news_tag_model !== null) {
            $i = 1;
            foreach ($news_tag_model as $row_news_tag) {
                $news_tag .= $row_news_tag->news_tag_value;
                if ($i < count($news_tag_model))
                    $news_tag .= ', ';
                $i++;
            }
        }

        $this->render('view', array(
            'model' => $this->loadModel($id),
            'news_tag' => $news_tag,
        ));
    }

    public function ActionMigrationActivation() {
     $con = mysql_connect('localhost', 'root', '');
	$db = false;
	if($con){
		$db = mysql_select_db('globalin_finite', $con);
	}
	
	if($db){
		$rs_row = mysql_query("SELECT member_network_id,member_network_id FROM sys_member WHERE year(member_join_datetime) >= 2011 ");
		$total = mysql_num_rows($rs_row);
			
		$limit = 1000;
		
		$t = ceil($total/$limit); $climit = 0; $row_active = 0;
		
		$rr = '';
		for($i = 0;$i < $t;$i++){
			$offset = $i*$limit;
			
			if(($total-$limit) >= $limit){
				$row_active = 2000;
			} else {
				$row_active = ($total-$limit);
			}
			
			$rs = mysql_query("SELECT member_network_id,member_network_id FROM sys_member WHERE year(member_join_datetime) >= 2011 LIMIT ".$offset.", ".$limit);
			
			if($rs){
				$row = 'INSERT INTO sys_member_activation (member_activation_network_id, member_activation_start_date, member_activation_end_date,
							member_activation_note, member_activation_input_administrator_id) VALUES '; 
				
				$i = 0;
				
				while($member = mysql_fetch_assoc($rs)){
					$expire = @date("Y-m-d H:i:s", mktime(0, 0, 0, date("m", strtotime($member['member_join_datetime'])), date("d", strtotime($member['member_join_datetime'])), date("Y", strtotime($member['member_join_datetime'])) + 1));
					
					$row .= " ('".$member['member_network_id']."', '".$member['member_join_datetime']."', '".$expire."', '', 1) ";
					
					if($i < $row_active){
						$row .= ' , ';
					}
				}
				
				
				mysql_query($row);
				//$rr .= $row.'<br/><br/>';
			} else {
				die(mysql_error());
			}
			
			sleep(1);
		}
		
		echo $rr;
	} else {
		die(mysql_error());
	}
}


    public function ActionTes() {
        echo "coba";
        die();
    }

    public function actionCreate() {
        $model = new site_news;

        if (isset($_POST['site_news'])) {
            $model->attributes = $_POST['site_news'];
            $model->news_admin_id = Yii::app()->user->administrator_id;
            $model->news_input_datetime = date("Y-m-d H:i:s");

            /* penanganan image */
            $image_file = CUploadedFile::getInstance($model, 'news_image');
            // has the user uploaded a new file?
            if ($image_file) {
                if (!is_dir(Yii::getPathOfAlias('webroot') . '/images/news/' . $model->news_image)) {
                    mkdir(Yii::getPathOfAlias('webroot') . '/images/news/' . $model->news_image);
                    chmod(Yii::getPathOfAlias('webroot') . '/images/news/' . $model->news_image, 0777);
                }
                $model->news_image = $image_file->name;
                //$picture_file->SaveAs(Yii::app()->getBasePath().'/images/news' . $picture_name);
                $image_file->SaveAs(Yii::getPathOfAlias('webroot') . '/images/news/' . $image_file->name);
            }

            if ($model->save()) {
                $news_id = Yii::app()->db->getLastInsertID();
                $arr_news_tag = explode(',', $_POST['site_news']['news_tag']);
                foreach ($arr_news_tag as $id => $value) {
                    Yii::app()->db->createCommand()->insert('site_news_tag', array(
                        'news_tag_news_id' => $news_id,
                        'news_tag_value' => trim($value),
                    ));
                }
                $this->redirect(array('list'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        if (isset($_POST['site_news'])) {
            $model->attributes = $_POST['site_news'];
            if ($model->save())
                $this->redirect(array('update', 'id' => $model->news_id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('site_news');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionList() {
        $model = new site_news('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['site_news']))
            $model->attributes = $_GET['site_news'];

        $this->render('list', array(
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = site_news::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'site-news-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
